from django.contrib.auth.backends import ModelBackend
import re, logging
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from .import constants
from .models import User

# 配置日志
logger = logging.getLogger("django")


def get_user_by_account(account):
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            # 手机号登陆
            user = User.objects.get(mobile=account)
        else:
            # 用户名
            user = User.objects.get(username=account)

    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    # 重写认证方法实现多账号登陆
    def authenticate(self, request, username=None, password=None, **kwargs):

        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user
        else:
            return None


# 生成邮箱访问令牌
def generate_verify_email_url(user):
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.ACCESS_TOKEN_EXPIRES)
    data = {"user_id": user.id, "email": user.email}
    token = serializer.dumps(data).decode("utf-8")
    verify_url = settings.EMAIL_VERIFY_URL + "?token=" + token
    return verify_url


# 校验邮箱访问令牌
def check_verify_email_token(token):
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.ACCESS_TOKEN_EXPIRES)
    try:
        data = serializer.loads(token)
    except Exception as e:
        logger.error(e)
        return None
    else:
        # 提取数据
        user_id = data.get("user_id")
        email = data.get("email")
        try:
            # 校对数据
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user


